using System;
using Wikey.Extensibility.Classes;
using Wikey.Extensibility.Enums;
using Wikey.Extensibility.Interfaces;
using Wikey.Interfaces.Attributes;

namespace Wikey.Transformation.Transformers
{
    [Transformer(Command = "Files")]
    public class FileTransformer : ITransformer
    {
        //Will be removed to automatically operate by Reflection.
        public string Command
        {
            get { return "Files"; }
        }

        public TransformationResult Apply(IExpressionFunction function)
        {
            ContentRenderer = Render;

            if(! String.IsNullOrEmpty( function.Value ))
            {
                FileId = 0;
                FileName = function.Value;
                FilePath = function.Value;
            }
            else
            {
                foreach (var expressionParameter in function.Parameters)
                {
                    if( expressionParameter.Name.Equals("Filename" , StringComparison.InvariantCultureIgnoreCase))
                    {
                        FileName = expressionParameter.Value;
                    }

                    if(expressionParameter.Name.Equals("Filepath" , StringComparison.InvariantCultureIgnoreCase))
                    {
                        FilePath = expressionParameter.Value;
                    }

                    if( String.IsNullOrEmpty(FilePath))
                    {
                        FilePath = FileName;
                    }
                    
                    if( expressionParameter.Name.Equals("Type" , StringComparison.InvariantCultureIgnoreCase) )
                    {
                        ContentRenderer = RenderATagWithImage;
                    }
                }
            }

            return new TransformationResult(TransformationResultType.Html, ContentRenderer());
        }

        private string Render()
        {
            return String.Format(
                        "<a href='{0}'>{1}</a>", FilePath, FileName
                    );
        }

        private string RenderATagWithImage()
        {
            return String.Format(
                        "<a href='{0}'><img src='{0}' title='{1}'/>&nbsp;{1}</a>", FilePath, FileName
                );
        }

        public bool AcceptDirectParameter {
            get; set;
        }

        public Func<string> ContentRenderer { get; set; }

        [Parameter(Required=true)]
        public string FileName { get; set; }

        public string FilePath { get; set; }

        [Parameter]
        public int FileId { get; set; }
    }

   
}